'''
Description:  外星人项目入口文件
Author: gn
Date: 2024-04-18 12:54:51
LastEditors: sevenFunuction 1593215788@qq.com
LastEditTime: 2024-06-24 22:33:45
'''

import sys
import pygame
from settings import Settings
from ship import Ship
from bullet import Bullet
from alien import Alien
from config.logger_config import setup_logger

class AlienInvasion:  # 类名首字母大写
    """管理游戏资源和行为的类"""

    def __init__(self):
        """初始化游戏并创建游戏资源"""
        pygame.init()
        

        # 配置全局日志输出
        setup_logger()
        
        # 设置屏幕宽度
        self.settings = Settings()
        
        # 设置宽度为全屏跨度
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        
        # 定义子弹盒子
        self.bullets = pygame.sprite.Group()
        
        # 定义外星人盒子
        self.aliens = pygame.sprite.Group()
        
        # 创建外星人
        self._create_alien()
          
        '''报错当前屏幕宽度'''
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        
        pygame.display.set_caption("Alien Invasion") # 设置游戏窗口标题
        
        self.ship = Ship(self)

    def run_game(self):
        """开始游戏的主循环，每次循环都会生成一个新屏幕"""
        while True:
            
            self._check_events()
            
            # 跟新飞船
            self.ship.update()
            
            # 更新子弹位置
            self.bullets.update()
            
            self._delete_hide_bullet()
            
            # 刷新屏幕
            self._update_screen()        
            
    '''
    description: 监听键盘事件
    param {*} self
    return {*}
    author: gn
    '''    
    def _check_events(self):
        
        """响应按键和鼠标事件"""
        for event in pygame.event.get():
          if event.type == pygame.QUIT:
              pygame.quit()
              sys.exit()
          elif event.type == pygame.KEYDOWN:
            self._check_keydown_events(event)
          elif event.type == pygame.KEYUP:
            self._check_keyup_events(event)
    
    '''
    description: 删除在消失在视口内的子弹，防止内存泄漏
    param {*} self
    return {*}
    author: gn
    '''    
    def _delete_hide_bullet(self):
      if len(self.bullets) == 0: return
      
      for bullet in self.bullets.copy():
        if bullet.rect.bottom <= 0:
          self.bullets.remove(bullet)
    
    '''
    description: 响应按键
    param {*} self
    param {*} event
    return {*}
    author: gn
    '''  
    def _check_keydown_events(self, event):
      if event.key == pygame.K_RIGHT:
        self.ship.moving_right = True
      elif event.key == pygame.K_LEFT:
        self.ship.moving_left = True
      elif event.key == pygame.K_SPACE:
        # 生成子弹
        self._fire_bullet()
      elif event.key == pygame.K_ESCAPE:
        sys.exit()
        
        
    '''
    description: 响应松开
    param {*} self
    return {*}
    author: gn
    '''   
    def _check_keyup_events(self, event):
      if event.key == pygame.K_RIGHT:
        self.ship.moving_right = False
      elif event.key == pygame.K_LEFT:
        self.ship.moving_left = False
              
    def _update_screen(self):
      """更新屏幕上的图像，并切换到新屏幕"""
      self.screen.fill(self.settings.bg_color) # 填充背景颜色
      self.ship.blitme() # 绘制飞船
      
      # 循环绘制子弹
      for b in self.bullets.sprites():
        b.draw_bullet()
      
      # 绘制外星人
      self.aliens.draw(self.screen)
          
      # 让最近绘制的屏幕可见
      pygame.display.flip()
      
    '''
    description: 发射子弹
    param {*} self
    return {*}
    author: gn
    '''    
    def _fire_bullet(self):
      
      # 小于允许创建的子弹数量时，创建新子弹
      if len(self.bullets) <= self.settings.allow_draw_bullet:
        new_bullet = Bullet(self)
        self.bullets.add(new_bullet)
    
    '''
    description: 
    return {*}
    author: gn
    '''    

    def _create_alien(self):
        alien = Alien(self)
        alien_width = alien.rect.width
        
        # 左右空留一个外星人宽度
        available_space_x = self.settings.screen_width - (2 * alien_width)
        # 一个外星人占两自身宽度
        number_aliens_x = available_space_x // (2 * alien_width)
        
        for alien_number in range(number_aliens_x):
            alien = Alien(self)
            alien.x = alien_width + 2 * alien_width * alien_number
            alien.rect.x = alien.x
            self.aliens.add(alien)
            
        
        
# 运行初始化配置
if __name__ == "__main__":
    # 创建一个实例，并运行游戏
    ai = AlienInvasion() # type: ignore
    ai.run_game()





 
